﻿using Abp.Extensions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Routing;
using Mt.Site.Core.Navigations.Route;
using Mt.Site.Core.Web;
using Mt.Site.Web.Url;

namespace Mt.Site.Core.Url
{
    public class NewUrlGetter : UrlGetter
    {
        private readonly IRouteChecker _routeChecker;

        public NewUrlGetter(
            IRouteChecker routeChecker,
            ITenancyNameCache tenancyNameCache,
            IUrlHelperFactory urlHelperFactory,
            IActionContextAccessor actionContextAccessor,
            IRouteDataChecker routeDataChecker) 
            :base(
             routeChecker,
             tenancyNameCache,
             urlHelperFactory,
             actionContextAccessor,
             routeDataChecker)
        {
            _routeChecker = routeChecker;
        }

        /// <summary>
        /// 依据配置将url中的tenancyName和cultureName显示或隐藏
        /// </summary>
        /// <param name="url">完整的前台页面链接（带有tenancyName和cultureName前缀）</param>
        /// <returns></returns>
        public override string TryHiddenPrefix(string url)
        {
            var prefix = $"/{TenancyName}/{CultureName}";
            if (!url.StartsWith(prefix, System.StringComparison.OrdinalIgnoreCase))
            {
                return url;
            }
            if (IsNeedTenancyName && IsNeedCultureName)
            {
                return url;
            }

            else if (IsNeedTenancyName)
            {
                url = url.Remove($"/{TenancyName}".Length, $"/{CultureName}".Length);
            }
            else if (IsNeedCultureName)
            {
                url = url.Substring($"/{TenancyName}".Length);
            }
            else
            {
                url = url.Substring(prefix.Length);
            }

            if (url.IsNullOrEmpty())
            {
                url = "/";
            }
            return url.ToLower();
        }

        public override string RealUrlToDiyUrlAndRemovePrefix(string url)
        {
            _routeChecker.RealUrlToDiyUrl(ref url);

            url = url.RemovePreFix($"/{TenancyName}/{CultureName}");


            if (url.IsNullOrEmpty())
            {
                url = "/";
            }

            return url.ToLower();
        }
    }
}
